<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="企业的唯一标识码，用于区分不同客户" prop="enterpriseCode">
        <el-input
          v-model="queryParams.enterpriseCode"
          placeholder="请输入企业的唯一标识码，用于区分不同客户"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="企业的全称或常用名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业的全称或常用名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户账号名称，标识客户在系统中的账号" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入客户账号名称，标识客户在系统中的账号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系人的手机号码，用于联系客户" prop="mobileNumber">
        <el-input
          v-model="queryParams.mobileNumber"
          placeholder="请输入联系人的手机号码，用于联系客户"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户的邮箱地址，用于发送通知或重要信息" prop="emailAddress">
        <el-input
          v-model="queryParams.emailAddress"
          placeholder="请输入客户的邮箱地址，用于发送通知或重要信息"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="记录创建的具体时间（年-月-日 时:分:秒），默认为当前时间" prop="creationTime">
        <el-date-picker
          v-model="queryParams.creationTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="备注，用于记录其他相关信息或特别说明" prop="notes">
        <el-input
          v-model="queryParams.notes"
          placeholder="请输入备注，用于记录其他相关信息或特别说明"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="布尔值，表示该记录是否处于启用状态（如 TRUE 表示启用，FALSE 表示停用），默认为 TRUE" prop="isEnabled">
        <el-select
          v-model="queryParams.isEnabled"
          placeholder="请选择布尔值，表示该记录是否处于启用状态（如 TRUE 表示启用，FALSE 表示停用），默认为 TRUE"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['customer:account-management:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['customer:account-management:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="企业编号" align="center" prop="enterpriseCode" />
      <el-table-column label="企业名称" align="center" prop="enterpriseName" />
      <el-table-column label="客户账号姓名" align="center" prop="accountName" />
      <el-table-column label="手机号" align="center" prop="mobileNumber" />
      <el-table-column label="邮箱地址" align="center" prop="emailAddress" />
      <el-table-column label="备注" align="center" prop="notes" />
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="创建时间" align="center" prop="creationTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="是否启用" align="center" prop="isEnabled" />
      <el-table-column label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['customer:account-management:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="openResetPwdDialog(scope.row)"
          >
            重置密码
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['customer:account-management:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AccountManagementForm ref="formRef" @success="getList" />

  <!-- 重置密码弹窗 -->
  <el-dialog v-model="resetPwdDialogVisible" title="重置密码" width="500px">
    <el-radio-group v-model="resetPwdForm.type" style="margin-bottom: 20px;">
      <el-radio label="custom">重置为指定密码</el-radio>
      <el-radio label="init">重置为初始密码</el-radio>
    </el-radio-group>
    <div v-if="resetPwdForm.type === 'custom'" style="margin: 20px 0;">
      <el-input
        v-model="resetPwdForm.password"
        type="password"
        placeholder="请输入新密码"
        show-password
        style="width: 300px;"
      />
    </div>
    <div v-else style="margin: 20px 0; color: #aaa;">
      初始密码为123456
    </div>
    <template #footer>
      <el-button @click="resetPwdDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleResetPwd">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AccountManagementApi, AccountManagementVO } from '@/api/customer/accountmanagement'
import AccountManagementForm from './AccountManagementForm.vue'

/** 客户账号管理表，用于存储和管理客户的账号信息，包括企业编号、名称、账号名称、联系方式、创建人等信息 列表 */
defineOptions({ name: 'AccountManagement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AccountManagementVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  enterpriseCode: undefined,
  enterpriseName: undefined,
  accountName: undefined,
  mobileNumber: undefined,
  emailAddress: undefined,
  creationTime: [],
  notes: undefined,
  isEnabled: undefined,
  operationDescription: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AccountManagementApi.getAccountManagementPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AccountManagementApi.deleteAccountManagement(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AccountManagementApi.exportAccountManagement(queryParams)
    download.excel(data, '客户账号管理表，用于存储和管理客户的账号信息，包括企业编号、名称、账号名称、联系方式、创建人等信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 重置密码弹窗相关 */
const resetPwdDialogVisible = ref(false)
const resetPwdForm = reactive({
  type: 'custom', // 'custom' or 'init'
  password: '',
})
const currentEmail = ref('')

const openResetPwdDialog = (row: any) => {
  resetPwdDialogVisible.value = true
  currentEmail.value = row.emailAddress // 这里用表格里的邮箱字段
  resetPwdForm.type = 'custom'
  resetPwdForm.password = ''
}

const handleResetPwd = async () => {
  let email = currentEmail.value
  let flag = resetPwdForm.type === 'custom' ? 1 : 0
  let password = resetPwdForm.type === 'custom' ? resetPwdForm.password : undefined

  // 预留接口：你可以在这里调用API
  await AccountManagementApi.resetPassword(email, flag, password)
  resetPwdDialogVisible.value = false
  message.success('操作成功')
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
